package com.csc.banking.security;

import java.util.Date;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;

import com.csc.banking.dao.UserDetailsDao;
import com.csc.banking.model.UserAttempts;

public class LimitLoginAuthentication extends DaoAuthenticationProvider {
	
		UserDetailsDao userDetailsDao;
		@Override
		public Authentication authenticate(Authentication au)
				throws AuthenticationException {
			
			try{
				System.out.println("Authentication:"+au.getName());
				
				Authentication auth = super.authenticate(au);				
				return auth;
			}catch(BadCredentialsException e){
				System.out.println("Bad Credentials Exception is:"+au.getName());
				userDetailsDao.updateFailAttempts(au.getName());				
				throw e;
			}catch(LockedException e){
				String error = "";
				System.out.println("LockedException is:"+au.getName());
				UserAttempts userAttempts = userDetailsDao.getUserAttempts(au.getName());
				if (userAttempts != null) {
					Date lastAttempts = userAttempts.getLastModified();
					error = "User account is locked!<br>Username : " + au.getName()
							+ "<br>Last Attempts : " + lastAttempts;
				} else {
					error = e.getMessage();
				}
				throw new LockedException(error);
			}
			
		}
		@Override
		public void setUserDetailsService(UserDetailsService userDetailsService) {
		// TODO Auto-generated method stub
			super.setUserDetailsService(userDetailsService);	
		}
		
		public UserDetailsDao getUserDetailsDao() {
			return userDetailsDao;
		}
		public void setUserDetailsDao(UserDetailsDao userDetailsDao) {
			this.userDetailsDao = userDetailsDao;
		}
		
}
